<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      <el-input
        @keyup.enter.native="getData"
        clearable
        style="margin-right: 15px"
        :style="{ width: inputWid(param.machineId) }"
        :show-word-limit="true"
        class="filter-item"
        v-model="param.machineId"
        placeholder="请输入机台号"
      ></el-input>
      <!-- style="width: 200px;margin-right:15px;" -->
      <el-input
        @keyup.enter.native="getData"
        clearable
        style="margin-right: 15px"
        :style="{ width: inputWid(param.technologyNo) }"
        class="filter-item"
        v-model="param.technologyNo"
        placeholder="请输入品号"
      ></el-input>
      <el-input
        @keyup.enter.native="getData"
        clearable
        style="margin-right: 15px"
        :style="{ width: inputWid(param.orderPlanNo) }"
        class="filter-item"
        v-model="param.orderPlanNo"
        placeholder="请输入计划批号"
      ></el-input>
      <el-input
        @keyup.enter.native="getData"
        clearable
        style="margin-right: 15px"
        :style="{ width: inputWid(param.planNo) }"
        class="filter-item"
        v-model="param.planNo"
        placeholder="请输入排产序号"
      ></el-input>
      
      <el-input
        @keyup.enter.native="getData"
        clearable
        style="margin-right: 15px"
        :style="{ width: inputWid(param.deviceBarcode) }"
        class="filter-item"
        v-model="param.deviceBarcode"
        placeholder="请输入工序条码"
      ></el-input>
      <el-date-picker
        clearable
        v-model="dateOptions"
        type="datetimerange"
        value-format="yyyy-MM-dd HH:mm:ss"
        format="yyyy-MM-dd HH:mm:ss"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="请选择开始时间"
        end-placeholder="结束时间"
        align="right"
        style="margin-right:15px;"
        />

        <el-select
        clearable
        v-model="param.isEnd" 
        placeholder="请选择状态" 
        style="margin-right:15px;margin-top:15px;width: 150px">
            <el-option 
            :value="item" 
            :label="item" v-for="(item,index) in this.statusList" 
            :key="index"/>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="getData">查询</el-button>
    </div>

    <!-- table 表格 -->
    <el-table  :data="tableInfo" :height="height" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%">
      <el-table-column label="序号" type="index" align="center" width="70px"/>
      <el-table-column label="工序名称" prop="pmProcessName" align="center"/>
      <el-table-column label="机台号" prop="machineId" align="center"/>
      <el-table-column label="品号" prop="technologyNo" align="center"/>
      <el-table-column label="品名" prop="technologyName" align="center"/>
      <el-table-column label="规格" prop="specification" align="center"/>
      <el-table-column label="排产序号" prop="planNo" align="center"/>
      <el-table-column label="计划批号" prop="orderPlanNo" align="center"/>
      <el-table-column label="工序条码"  prop="deviceBarcode" align="center"/>
      <el-table-column label="工单开始日期"  prop="beginTime" align="center" width="120px"/>
      <el-table-column label="工单结束日期" prop='finishTime' align="center" width="120px"/>
      <el-table-column label="零件数" prop='count' align="center"/>
      <el-table-column label="工艺工序上传" prop="pmProcessName" align="center">
        <template slot-scope="scope">
          <div class="fx">
            {{
              scope.row.pmProcessName? "已上传":"未上传"
            }}
           </div>
        </template>
      </el-table-column>
      <el-table-column label="计划排产上传" prop="planNo" align="center">
        <template slot-scope="scope">
          <div class="fx">
            {{
              scope.row.planNo? "已上传":"未上传"
            }}
           </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="isEnd" align="center">
        <template slot-scope="scope">
          <div class="fx">
            {{
              scope.row.isEnd  == '1'? "完工"
              : scope.row.isEnd  == '2'? "停产"
              : scope.row.isEnd  == '0'
                ? "未完工"
                : "-"
            }}
           </div>
        </template>
      </el-table-column>
      <!-- <el-table-column  label="标准工时(s)" prop='time' align="center"/> -->
      <!-- 对员工数据进行编辑与删除操作 -->
      <el-table-column fixed="right" label="操作"  align="center" width="220" v-if="userInfo.roleId == 0 || userInfo.roleId == 4 || userInfo.roleId == 14 || userInfo.roleId == 25 || userInfo.roleId == 38 || userInfo.roleId == 40 || userInfo.roleId == 41 || userInfo.roleId == 43">
        <template slot-scope="scope" >
            <el-button size="mini" type="primary" v-waves icon="el-icon-refresh-left" :loading="scope.row.updateStaff" @click="submitupdate(scope.row,scope.$index)"></el-button>
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index,scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
   <div slot="tip" class="el-upload__tip">提示：s指的是秒</div>
   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>

    <el-button type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>

    <!-- 修改工单信息 -->
    <el-dialog title="工单信息修改" :visible.sync="dialogFormVisible" width="700px">
      <el-form :model="modifyform" :rules="rules" ref="modifyform">

        <el-form-item label="排产序号" :label-width="formLabelWidth">
          <el-input v-model="modifyform.planNo" :disabled="true" style="width:400px" />
        </el-form-item>

        <el-form-item label="工序条码" :label-width="formLabelWidth">
          <el-input v-model="modifyform.deviceBarcode" :disabled="true" style="width:400px" />
        </el-form-item>

        <el-form-item label="工序" :label-width="formLabelWidth">
          <el-input v-model="modifyform.pmProcessName" :disabled="true" style="width:400px" />
        </el-form-item>

        <el-form-item label="机器编号" :label-width="formLabelWidth" style="width:550px" prop="machineIdTags">
          <el-tag
          :key="tag"
          v-for="tag in modifyform.machineIdTags"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)">
          {{tag}}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        >
        </el-input>

        <el-button v-else class="button-new-tag" size="small" @click="showInput">添加机台</el-button>

        </el-form-item>

        <el-form-item label="日期" :label-width="formLabelWidth">
          <el-date-picker
            v-model="dateOptions1"
            :clearable="false"
            type="datetimerange"
            range-separator="至"
            start-placeholder="请选择工单开始日期"
            format="yyyy-MM-dd HH"
            value-format="yyyy-MM-dd HH:mm:ss"
            popper-class="tpc"
            end-placeholder="结束日期"
            style="width: 400px;">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="零件数" :label-width="formLabelWidth" prop="count">
          <el-input v-model="modifyform.count" style="width:400px" />
        </el-form-item>

        <!-- <el-form-item label="标准工时" :label-width="formLabelWidth" prop="time">
          <el-input v-model="modifyform.time" style="width:400px" placeholder="请输入标准工时（单位为秒）" />
        </el-form-item> -->

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('modifyform')">确 定</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import { findPlanMachine,delPlanMachine,updPlanMachine,synchronousRecording } from '../../api/orderAndMachine'
export default {
    name: 'orderList',
    data () {
        return {
            param: {
              planNo: '',                         //排产序号
              deviceBarcode: '',                  //工序条码
              machineId: '',                     //机台号
              isEnd: ''
            },
            listQuery: {
                page: 1,                           //页码
                limit: 10                         //每页多少条记录
            },
            formLabelWidth: '100px',
            searchInputStyle: 'width: 200px;margin-right:15px;',
            total: 0,     //数据的总数
            tableInfo: [],                                 //表格数据
            loadingList: false,                              //加载显示
            dateOptions: this.getNowTime(),
            pickerOptions: {
                shortcuts: [{
                  text: '最近一周',
                  onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                    picker.$emit('pick', [start, end]);
                  }
                }, {
                  text: '最近一个月',
                  onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                    picker.$emit('pick', [start, end]);
                  }
                }, {
                  text: '最近三个月',
                  onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                    picker.$emit('pick', [start, end]);
                  }
                }]
            },
            modifyform: {},            //编辑表单
            dialogFormVisible: false,  //是否显示修改表单弹窗
            inputVisible: false,        //编辑表单的是否显示添加机台tag
            inputValue: '',             //编辑表单的添加机台输入框
            dateOptions1: [],           //编辑表单的时间选择器
            rules: {
              machineIdTags: [
                { required: true, message: '请添加机器编号', trigger: 'blur' },
              ],
              count: [
                { required: true, message: '请输入零件数', trigger: 'blur' },
              ]
            },
            loading:false,
            userInfo: this.$store.state.user.userInfo,
            statusList: ['未完工','完工','停产'],
            height: 650
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
      transformDat(res) {
        // console.log('%c导出质量系数excel数据:','color:green;font-size:16px;')
        // console.log(res)
        const mapInfo = {
          index: '序号',
          pmProcessName: '工序名称',
          machineId: '机台号',
          technologyNo: '品号',
          technologyName: '品名',
          specification: '规格',
          planNo: '排产序号',
          orderPlanNo: '计划批号',
          deviceBarcode: '工序条码',
          beginTime: '工单开始日期',
          finishTime: '工单结束日期',
          count: '零件数',
          processStatus: '工艺工序上传',
          planNoStatus: '计划排产上传',
          isEndStatus: '状态',
        }
        // 对data进行格式化
        // 取出所有的属性名
        const props = Object.keys(res[0]) // ['id','']
        console.log(props)
        // 将属性名从英文转为中文
        const header = props.map(zhkey => mapInfo[zhkey])
        console.log('中文的表头', header)
        // const data=[['xxxx','总裁办'，'13800000']]
        const data = res.map(obj => Object.values(obj))
        return { header, data }
      },
      // 导出excel
      async hExportExcel() {
        this.loading = true
        let query = Object.assign({},this.listQuery)
        if(this.param.orderPlanNo) {query.orderPlanNo = this.param.orderPlanNo}
        if(this.param.technologyNo) { query.technologyNo = this.param.technologyNo }
        if(this.param.planNo) {query.planNo = this.param.planNo}
        if(this.param.deviceBarcode) {query.deviceBarcode = this.param.deviceBarcode}
        if(this.param.machineId) {query.machineId = this.param.machineId}
        if(this.param.isEnd != '') { query.isEnd = this.param.isEnd == '未完工'?0:this.param.isEnd == '完工'?1:2 }
        if(this.dateOptions){
          if(this.dateOptions.length) {
            query.beginTime = this.dateOptions[0]
            query.finishTime = this.dateOptions[1]
          }
        }
        query.page = 1
        query.limit = 10000
        console.log('%c导出excel传的参数query:','color:green;font-size:16px;')
        console.log(query)

        let arr = await findPlanMachine(query)
        if(!arr.data.list.length) {
          this.loading = false
          this.$message({
            message: '暂无数据',
            type: 'warning'
          })
          return
        }
        arr.data.list.forEach(item=>{
          delete item.practicalCount
          item.processStatus = item.pmProcessName?'已上传':'未上传'
          item.planNoStatus =  item.planNo?'已上传':'未上传'
          item.isEndStatus =  item.isEnd == '1'?'完工':item.isEnd == '2'?'停产':item.isEnd == '0'?'未完工':'-'
        })
        const { header, data } = this.transformDat(this.setSort(arr.data.list))
          import('@/vendor/Export2Excel').then(excel => {
          // excel表示导入的模块对象
          console.log(excel)
          excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '工单excel', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
          })
        })
        this.loading = false
      },
      // 排序函数
      setSort(arr){
        let newArr = JSON.parse(JSON.stringify(arr))
        let arr1 = []
        newArr.forEach((item,index)=>{
          let obj = {
            index: index+1,
            pmProcessName: item.pmProcessName,
            machineId: item.machineId,
            technologyNo: item.technologyNo,
            technologyName: item.technologyName,
            specification: item.specification,
            planNo: item.planNo,
            orderPlanNo: item.orderPlanNo,
            deviceBarcode: item.deviceBarcode,
            beginTime: item.beginTime,
            finishTime: item.finishTime,
            count: item.count,
            processStatus: item.processStatus,
            planNoStatus: item.planNoStatus,
            isEndStatus: item.isEndStatus,
          }
          arr1.push(obj)
        })
        return arr1
      },
      clearData(){
        this.listQuery.page = 1
        this.listQuery.limit = 10
      },
      getData(){
        this.clearData()
        this.handleFilter()
      },
      async handleFilter() {
          this.loadingList = true
          let query = Object.assign({},this.listQuery)
          if(this.param.planNo) {query.planNo = this.param.planNo}
          if(this.param.deviceBarcode) {query.deviceBarcode = this.param.deviceBarcode}
          if(this.param.machineId) {query.machineId = this.param.machineId}
          if(this.param.isEnd != '') { query.isEnd = this.param.isEnd == '未完工'?0:this.param.isEnd == '完工'?1:2  }
          if(this.param.orderPlanNo) { query.orderPlanNo = this.param.orderPlanNo }
          if(this.param.technologyNo) { query.technologyNo = this.param.technologyNo }
          if(this.dateOptions){
            if(this.dateOptions.length) {
              query.beginTime = this.dateOptions[0]
              query.finishTime = this.dateOptions[1]
            }
          }
          let data = await findPlanMachine(query)
          let errmsg = data.msg
          let datas = ''
          if(data.data){ datas = JSON.parse(JSON.stringify(data.data.list)) }
          console.log(data)
          if(data.code == '1'){
              this.loadingList = false
              this.total = data.data.totle
              if(!datas) {
                this.tableInfo = datas
                this.height = ''
                return
              }
              datas.forEach(item => {
                item.machineIdTags = item.machineId.split(',')
              });
              this.total = data.data.totle
              this.tableInfo = datas
              if(this.tableInfo.length<10){this.height = ''} else {this.height = 650}
            } else {
              this.$message({
                  message: errmsg,
                  type: 'error'
              })
          }
      },
      // 删除记录按钮,使用elementui的messageBox弹框组件
      handleDelete(index,row) {
          this.$confirm('这将会永久删除该行数据，是否继续?', '警告', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
          }).then(() => {
              this.delPlanMachine(index,row)
          }).catch(() => {
              this.$message({
                type: 'info', 
                message: '已取消删除'
              })
          })
      },
      // 删除记录
      async delPlanMachine(index,row){
        let query = {
          machineId: row.machineId,
          deviceBarcode: row.deviceBarcode,
          planNo: row.planNo
        }
        let data = await delPlanMachine(query)
        let errmsg = data.msg
        if(data.code == '1'){
          this.tableInfo.splice(index, 1)
          this.total = this.total - 1
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          } else {
            this.$message({
                message: errmsg,
                type: 'warning'
            })
        }
      },
      // 验证编辑的表单
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log('submit!!');
            this.modifyMachine()
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 请求修改表单
      async modifyMachine(){
        let query = Object.assign({},this.modifyform)
        console.log(this.dateOptions1,query,this.modifyform)
        query.beginTime = this.dateOptions1[0]
        query.finishTime = this.dateOptions1[1]
        query.machineId = this.modifyform.machineIdTags.join(',')
        delete query.machineIdTags
        let data = await updPlanMachine(query)
        let errmsg = data.msg
        if(data.code == '1'){
          this.dialogFormVisible = false
          this.handleFilter()
            this.$message({
                message: errmsg,
                type: 'success'
            })
          } else {
            this.$message({
                message: errmsg,
                type: 'error'
            })
        }
      },
      // 编辑表单的信息
      handleEdit(item) {
        this.modifyform = Object.assign({},item)
        let dates = []
        dates.push(this.modifyform.beginTime)
        dates.push(this.modifyform.finishTime)
        this.dateOptions1 = dates
        this.dialogFormVisible = true
      },
      handleClose(tag) {
        this.modifyform.machineIdTags.splice(this.modifyform.machineIdTags.indexOf(tag), 1);
      },
      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.modifyform.machineIdTags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      // table表单下方的页码组件改变每页显示的数据条数
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.handleFilter()
      },
        // table表单下方的页码组件改变页面
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.handleFilter()
      },
      //初始默认执行(重点)
    getNowTime() {
      let dateTime = +new Date()+8*3600*1000
      const start = new Date(dateTime - 3600 * 1000 * 24 * 7)
        .toISOString()
        .replace('T', ' ')
        .split('.')[0] //默认开始时间7天前
      const end = new Date(dateTime)
        .toISOString()
        .replace('T', ' ')
        .split('.')[0]//默认结束时间当前时间
      console.log([start, end])
      return [start, end]
    },
    // 刷新
    async submitupdate(row,index){
      this.tableInfo[index].updateStaff = true
      let query = {
        deviceBarcode: row.deviceBarcode,
      }
      let res = await synchronousRecording(query)
      if(res.code == '1'){
          this.$message({
            message: '刷新成功！',
            type: 'success'
          })
          this.handleFilter()
          this.tableInfo[index].updateStaff = false
      } else {
          this.$message({
              message: res.msg,
              type: 'warning'
          })
      }
    },
    },
    // 进入页面获取table信息
    mounted() {
        this.handleFilter()
    }
}
</script>

<style>
.filter-item{
  margin-top: 6px;
}
.el-tag {
  margin-right: 10px;
}
.el-tag + .el-tag {
  margin-right: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.el-picker-panel__footer .el-picker-panel__link-btn.el-button--text  {
  display: none;
}
</style>